# 替换掉标准库的socket patch_socket 官网建议使用patch_all
from gevent import monkey
monkey.patch_all()
import gevent


def f(n):
    for i in range(n):
        print(gevent.getcurrent(), i)
        gevent.sleep(0)

# 创建一个新的greenlet协程对象，并运行它
g1 = gevent.spawn(f, 5)
g2 = gevent.spawn(f, 5)
g3 = gevent.spawn(f, 5)
g1.join()
g2.join()
g3.join()


def win():
    return 'You win!'


def fail():
    raise Exception('You failed!')


winner = gevent.spawn(win)
loser = gevent.spawn(fail)

print(winner.started)  # True
print(loser.started)  # True

# 在Greenlet中发生的异常，不会被抛到Greenlet外面。
# 控制台会打出Stacktrace，但程序不会停止
try:
    gevent.joinall([winner, loser])
except Exception as e:
    # 这段永远不会被执行
    print('This will never be reached')

print(winner.ready())  # True
print(loser.ready())  # True

print(winner.value)  # 'You win!'
print(loser.value)  # None

print(winner.successful())  # True
print(loser.successful())  # False

# 这里可以通过raise loser.exception 或 loser.get()
# 来将协程中的异常抛出
print(loser.exception)

from gevent import Timeout

timeout = Timeout(2)  # 2 seconds
timeout.start()


def wait():
    gevent.sleep(10)


try:
    gevent.spawn(wait).join()
except Timeout:
    print('Could not complete')

with Timeout(1):
    gevent.sleep(10)